//
//  PolyLinesView.swift
//  whetherDemo
//
//  Created by 姚东 on 2025/2/19.
//

import Foundation
import UIKit
import Charts

class PolyLinesView: UIView {

    private var lineChartView: LineChartView!

    // 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLineChart()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupLineChart()
    }

    // 设置 LineChartView 并进行基本配置
    private func setupLineChart() {
        lineChartView = LineChartView()
        lineChartView.frame = bounds
        lineChartView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(lineChartView)
        
        lineChartView.noDataText = "No data available" // 没有数据时的提示
        lineChartView.backgroundColor = .white
    }

    // 配置图表数据
    func setData(xValues: [String], yValues: [Double]) {
        var dataEntries: [ChartDataEntry] = []

        // 确保 x 和 y 数据的数量一致
        guard xValues.count == yValues.count else {
            print("Error: X and Y data arrays must have the same length")
            return
        }

        // 创建数据项
        for i in 0..<xValues.count {
            let dataEntry = ChartDataEntry(x: Double(i), y: yValues[i])
            dataEntries.append(dataEntry)
        }

        // 创建数据集并进行样式配置
        let chartDataSet = LineChartDataSet(entries: dataEntries, label: "Values")
        chartDataSet.colors = [NSUIColor.blue]  // 折线颜色
        chartDataSet.valueColors = [NSUIColor.black]  // 数值颜色
        chartDataSet.circleColors = [NSUIColor.red]  // 圆点颜色
        chartDataSet.drawFilledEnabled = true  // 填充折线下方的区域
        chartDataSet.fillColor = .blue  // 填充颜色
        chartDataSet.lineWidth = 2  // 线宽

        // 将数据集包装成 LineChartData 并赋值给图表
        let chartData = LineChartData(dataSet: chartDataSet)
        lineChartView.data = chartData
    }
}
